<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

function setMaps($map,$data,$fields,$type = 'EQ')
{
    switch ($type) {
        case 'EQ':
            $map[$fields] = $data;
            break;
        case 'NEQ':
            $map[$fields] = ['NEQ',$data];
            break;
        case 'LIKE':
            $map[$fields] = ['LIKE','%'.$data.'%'];
            break;
        
        default:
            // code...
            break;
    }
    return $map;
}

// 会员端的密码
function password($password = '',$salt = ''){
    $password = preg_match('/^\w{32}$/', $password) ? $password : md5($password);
    $password = md5($password . $salt);
    return $password;
}

// 后台的密码
function passwordAdmin($password = ''){
    // $m = strtoupper(md5($password));
    // $bkey = substr($m, 16, 16) . $m . substr($m, 0, 16);
    return md5($password);
}

# 处理提交上来的金额,把元改成分，去掉多余的小数位数
function formatMoneySave($amount)
{
    if($amount == '') return 0;
    try{
        $res = $amount * 100;
        return $res;

    }catch (Exception $e) {
        return 0;
    }
    
}
# 处理提交上来的金额,把元改成分，去掉多余的小数位数
function formatMoneyShow($amount)
{
    try{
        return bcdiv($amount,100,2);

    }catch (Exception $e) {
        return 0;
    }
    
}
# 处理提交上来的金额,把元改成分，去掉多余的小数位数
function formatMoneyShow2($amount)
{
    try{
        return bcdiv($amount,100,0);

    }catch (Exception $e) {
        return 0;
    }
    
}

function httpCurl($url, $params, $method = 'GET', $header = array(), $multi = false)
{
    date_default_timezone_set('PRC');
    $opts = array(
        CURLOPT_TIMEOUT        => 30,
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_HTTPHEADER     => $header,
        CURLOPT_COOKIESESSION  => true,
        CURLOPT_FOLLOWLOCATION => 1,
        CURLOPT_COOKIE         => session_name().'='.session_id(),
    );

    /* 根据请求类型设置特定参数 */

    switch(strtoupper($method)){

        case 'GET':

            $opts[CURLOPT_URL] = $url . '?' . http_build_query($params);
            break;
        case 'POST':                //判断是否传输文件
            $params = $multi ? $params : http_build_query($params);
            $opts[CURLOPT_URL] = $url;
            $opts[CURLOPT_POST] = 1;
            $opts[CURLOPT_POSTFIELDS] = $params;

            break;
        default:
            throw new Exception('不支持的请求方式！');
        }        

    /* 初始化并执行curl请求 */

    $ch = curl_init();
    curl_setopt_array($ch, $opts);        
    $data  = curl_exec($ch);        
    $error = curl_error($ch);
    curl_close($ch);        
    if($error) throw new Exception('请求发生错误：' . $error);     

    return  $data;
}

/**
 * 将数值金额转换为中文大写金额
 * @param $amount float 金额(支持到分)
 * @param $type   int   补整类型,0:到角补整;1:到元补整
 * @return mixed 中文大写金额
 */
function cny($amount, $type = 0) {
    // 判断输出的金额是否为数字或数字字符串
    if(!is_numeric($amount)){
        return "要转换的金额只能为数字!";
    }
 
    // 金额为0,则直接输出"零元整"
    if($amount == 0) {
        return "人民币零元整";
    }
 
    // 金额不能为负数
    if($amount < 0) {
        return "要转换的金额不能为负数!";
    }
 
    // 金额不能超过万亿,即12位
    if(strlen($amount) > 14) {
        return "要转换的金额不能为万亿及更高金额!";
    }
 
    // 预定义中文转换的数组
    $digital = array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    // 预定义单位转换的数组
    $position = array('仟', '佰', '拾', '亿', '仟', '佰', '拾', '万', '仟', '佰', '拾', '元');
 
    // 将金额的数值字符串拆分成数组
    $amountArr = explode('.', $amount);

    if(count($amountArr) == 1)
    {
        $amountArr[1] = '00';
    }
 
    // 将整数位的数值字符串拆分成数组
    $integerArr = str_split($amountArr[0], 1);
 
    // 将整数部分替换成大写汉字
    $result = '';
    $integerArrLength = count($integerArr);     // 整数位数组的长度
    $positionLength = count($position);         // 单位数组的长度
    $zeroCount = 0;                             // 连续为0数量
    for($i = 0; $i < $integerArrLength; $i++) {
        // 如果数值不为0,则正常转换
        if($integerArr[$i] != 0){
            // 如果前面数字为0需要增加一个零
            if($zeroCount >= 1){
                $result .= $digital[0];
            }
            $result .= $digital[$integerArr[$i]] . $position[$positionLength - $integerArrLength + $i];
            $zeroCount = 0;
        }else{
            $zeroCount += 1;
            // 如果数值为0, 且单位是亿,万,元这三个的时候,则直接显示单位
            if(($positionLength - $integerArrLength + $i + 1)%4 == 0){
                $result = $result . $position[$positionLength - $integerArrLength + $i];
            }
        }
    }
    if($type == 1000) return $result; // 不要整
    // 如果小数位也要转换
    if($type == 0) {
        // 将小数位的数值字符串拆分成数组
        $decimalArr = str_split($amountArr[1], 1);
        // 将角替换成大写汉字. 如果为0,则不替换
        if($decimalArr[0] != 0){
            $result = $result . $digital[$decimalArr[0]] . '角';
        }
        // 将分替换成大写汉字. 如果为0,则不替换
        if($decimalArr[1] != 0){
            $result = $result . $digital[$decimalArr[1]] . '分';
        }
    }else{
        $result = $result . '整';
    }
    return $result;
}

function xinghao($str, $start, $length = 0, $key = '*')
{
    // 通过$length的值来判断是否传入mb_substr函数的第三个参数$len
    $param = $length ? [$start, $length] : [$start];

    // 截取出需要替换的字符串
    $rep_str = mb_substr($str, ...$param);

    // 填充替换内容
    strlen($key) == mb_strlen($key) && $key = str_pad('', mb_strlen($rep_str), $key);

    // 获取实际的起始下标
    $start  = strlen(mb_substr($str, 0, $start));
    // 获取实际的替换长度
    $length  = strlen($rep_str);

    // 进行替换
    $result = substr_replace($str, $key, $start, $length);

    return $result;
}

/**
 * # 整数换算成时分秒
 * @param $cha 被换算的整数(秒数)
 * @param $type 是否有前导0
 * 
 */
function secToTime($cha,$type = true){
    if($cha <60){
        $seconds = $cha;
        if($type){
            $seconds = $seconds < 10 ? '0'.$seconds : $seconds;
        }
        return $seconds.'秒';
    }else if( $cha < 3600 ){
        $minutes = floor($cha/60);
        $seconds = $cha - ($minutes*60);
        if($type){
            if($minutes<10){
                $minutes='0'.$minutes;
            }
            if($seconds<10){
                $seconds='0'.$seconds;
            }
        }
        return $minutes.'分'.$seconds.'秒';
    }else if($cha<86400){
        $hour = floor($cha/3600);
        $minutes_cha = $cha - ($hour*3600);
        $minutes = floor($minutes_cha/60);
        $seconds = $minutes_cha - ($minutes*60);
        if($type){
            if($hour<10){
                $hour='0'.$hour;
            }
            if($minutes<10){
                $minutes='0'.$minutes;
            }
            if($seconds<10){
                $seconds='0'.$seconds;
            }
            return $hour.'小时'.$minutes.'分钟'.$seconds.'秒';
        }
    }else{
        $day = floor($cha/86400);
        $hour_cha = $cha - $day*86400;
        $hour = floor($hour_cha/3600);
        $minutes_cha = $hour_cha - $hour*3600;
        $minutes = floor($minutes_cha/60);
        $seconds = $minutes_cha - ($minutes*60);
        if($type){
            if($day<10){
                $day='0'.$day;
            }
            if($hour<10){
                $hour='0'.$hour;
            }
            if($minutes<10){
                $minutes='0'.$minutes;
            }
            if($seconds<10){
                $seconds='0'.$seconds;
            }
        }
        return $day.'天'.$hour.'小时'.$minutes.'分钟'.$seconds.'秒';
    }
}
/**
 * # 整数换算成时分秒
 * @param $cha 被换算的整数(秒数)
 * @param $type 是否有前导0
 * 
 */
function timeToDay($timestamp = 0){
    $currentTimestamp = time(); // 获取当前时间戳

    $cha = $currentTimestamp - $timestamp;
    if ($cha > 86400) {
        return '已过期';
    }
    if ($cha > 0 && $cha < 86400) {
        return '今天';
    }

    $diffInSeconds = $timestamp - $currentTimestamp; // 计算时间差（秒）
    $daysLeft = floor($diffInSeconds / (60 * 60 * 24)); // 转换为天数并舍去小数部分

    if($daysLeft == 0) return '明天';
    if($daysLeft == 1) return '后天';

    return '剩余'.$daysLeft . '天';
}

/**
 * [getJson 用于处理微信网页授权问题]
 * @param $url
 * @return mixed
 */
function getJson($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output, true);
}

function getQuestionType($question)
{
    $type = $question['type'];
    if($question['type'] == '选择题')
    {
        $res = explode(',', $question['result']);
        $correct = 0;
        foreach ($res as $r) {
            if($r == 1) $correct++;
        }
        // $question['correct'] = $correct;
        $type = $correct > 1 ? '多选题' : '单选题';
    }

    return $type;
}

// 新职位发布通知模板
function newTrainTemplate($templateId,$openid,$thing2,$time3,$time11)
{
    $data = [
        'thing2' => [
            'value' =>urlencode($thing2)
        ],

        'time3' => [
            'value' =>urlencode($time3)
        ],

        'time11' => [
            'value' =>urlencode($time11)
        ],

    ];

    $template = array(
        "touser" => $openid,
        "template_id" => $templateId,
        'miniprogram' => [
            'appid' => 'wxe59aec661b6257a7',
            'pagepath' => 'pages/switchPages/index',
        ],
        'topcolor' => '#ccc',
        'data' => $data
    );

    return $template;
}
// 微信支付相关的curl
function http_request($url,$rawData,$cert = false)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    // curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSLVERSION, 1);
    if($rawData)
    {
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type:text']);
    if($cert)
    {
        curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLCERT, ROOT_PATH.'cert/1563606101.pem');
        curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
        curl_setopt($ch,CURLOPT_SSLKEY, ROOT_PATH.'cert/1563606101_key.pem');
    }
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
